import { createRouter, createWebHistory } from "vue-router";

import PageLayout from "@/layout/page-layout.vue";
import Login from "./routes/modules/login"; //routes/modules/login
import h5Routes  from "./routes/modules/h5"; //routes/modules/login
import appRoutes from "./routes";
import createRouteGuard from "@/router/guard";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/", //根路由
      redirect: (to) => {
        const token = localStorage.getItem('token');
        return token ? '/home' : '/login'; // ✅ 已登录进入主框架，未登录去登录页
      },
      meta: {
        locale: "登陆页",
        requiresAuth: false,
      },
    },
    {
      path: '/H5Layout',
      name: '/H5Layout',
      component: () => import('@views/H5/H5Layout.vue'),
      meta: {
          requiresAuth: false,
      },
    },
    Login,
    {
      name: "root",
      path: "/layout",
      component: PageLayout,
      meta: {
        locale: "框架页",
        requiresAuth: true,
      },
      children: appRoutes,
    },
    {
      path: "/:pathMatch(.*)*", //404路由
      name: "notFound",
      component: () => import("@/views/not-found/index.vue"),
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
  
});

createRouteGuard(router);
// 从本地存储中读取路由信息并导航到相应路由


// router.beforeEach((to, from, next) => {
//   const token = localStorage.getItem('token');
//   if (to.path === '/login' && token) {
//       // 如果访问登录页且有 token，跳转到主页面
//       next('/home');
//   } else if (to.meta.requiresAuth && !token) {
//       // 如果访问需要验证的页面且没有 token，跳转到登录页
//       next('/login');
//   } else {
//       // 其他情况正常跳转
//       next();
//   }
// });
// router.beforeEach((to, from, next) => {
//   // 检查新版本
//   const localVersion =  localStorage.getItem("localVersion")

//   if(localVersion){
//     if(localVersion < `${import.meta.env.VITE_HTML_VERSION}`){

//       localStorage.setItem("localVersion", `${import.meta.env.VITE_HTML_VERSION}`)
//       Message.success({content:"检测到有新版本，稍后将自动刷新页面载入新版本！", duration: 4000});

//       setTimeout( function(){
//         window.location.reload();
//       }, 4 * 1000 );
//     }
//   }else{
//     localStorage.setItem("localVersion", `${import.meta.env.VITE_HTML_VERSION}`)
//   }
//   // 确保调用 next() 来继续路由导航
//   next();
// });

export default router;
